import { Translation } from 'react-i18next'
import { show } from './show'
import type { DialogConfirmProps } from './type'

/**
 * @description - 推荐
 * @description - 可以通过调用 Dialog 上的 `confirm` 方法直接打开对话框
 * @description - `confirm` 接受的参数同 `alert`
 * @description - 当对话框被关闭后，组件实例自动销毁
 * @description - 点击【确定】或【取消】操作按钮后都会触发`onClose`（closeOnAction - default: true）
 * @description - 它的返回值不是一个控制器对象，而是 `Promise<boolean>`
 */
export const confirm = (props: DialogConfirmProps): Promise<boolean> => {
  const {
    confirmText = (
      <Translation>
        {(t) => <>{t('common.gallery.Dialog.confirmText')}</>}
      </Translation>
    ),
    cancelText = (
      <Translation>
        {(t) => <>{t('common.gallery.Dialog.cancelText')}</>}
      </Translation>
    ),
    disabledConfirm,
    disabledCancle,
    onCancel,
    onConfirm,
    onClose,
  } = props

  return new Promise<boolean>((resolve) => {
    show({
      ...props,
      closeOnAction: true,
      onClose: () => {
        onClose?.()
        resolve(false) // 非点击按钮关闭 confirm 按 取消 处理
      },
      actions: [
        [
          {
            disabled: disabledCancle,
            key: 'cancel',
            text: cancelText,
            onClick: async () => {
              await onCancel?.()
              resolve(false)
            },
          },
          {
            bold: true,
            disabled: disabledConfirm,
            key: 'confirm',
            text: confirmText,
            onClick: async () => {
              await onConfirm?.()
              resolve(true)
            },
          },
        ],
      ],
    })
  })
}
